package com.gaotu.demo.transaction.daosupport;

import com.gaotu.demo.transaction.User;
import com.gaotu.demo.transaction.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class JdbcBasedDaoSupportUserRepository
        extends JdbcDaoSupport
        implements UserRepository {

    @Autowired
    public JdbcBasedDaoSupportUserRepository(DataSource dataSource){
        setDataSource(dataSource);
    }

    @Override
    public void save(User user) {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        this.getJdbcTemplate().update("insert into user (user_name, pwd, create_time, update_time) value (?,?,?,?)",
                user.getUserName(), user.getPwd(), user.getCreateTime(), user.getUpdateTime());
    }

    @Override
    public User getByUserName(String name) {
        return getJdbcTemplate().queryForObject("select id, user_name, pwd, create_time, update_time from user where user_name = ?", new UserRowMapper(), name);
    }

    class UserRowMapper implements RowMapper<User>{

        @Override
        public User mapRow(ResultSet resultSet, int rowNum) throws SQLException {
            User user = new User();
            user.setId(resultSet.getLong(1));
            user.setUserName(resultSet.getString(2));
            user.setPwd(resultSet.getString(3));
            user.setCreateTime(resultSet.getDate(4));
            user.setUpdateTime(resultSet.getDate(5));
            return user;
        }
    }
}
